#!/usr/bin/env python
# SpringDS v1.0 Beta 1 - a (cross-platform?) wrapper for the FRC Driver Station
# Copyright (C) 2012 River Hill HS Robotics Team (Albert H.)
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 
# This is the SpringDS Settings manager.
# 
# -*- coding: iso-8859-15 -*-
# generated by wxGlade 0.6.5 (standalone edition) on Wed Mar 21 14:30:52 2012

import wx
import wx.lib.filebrowsebutton as filebrowse
try:
    from agw import hyperlink as hl
except ImportError: # if it's not there locally, try the wxPython lib.
    import wx.lib.agw.hyperlink as hl
import SpringDSConfig
import SpringDSCrash
# begin wxGlade: extracode
# end wxGlade

# MsgBox - shows a message box.
# Types: wx.ICON_INFORMATION, wx.ICON_EXCLAMATION, wx.ICON_ERROR, wx.ICON_ERROR
def MsgBox(text, title, type, parent=None):
    dlg = wx.MessageDialog(parent, text, title, 
            wx.OK | type)
    dlg.ShowModal()

def ErrorBox(traceback):
    SDSCrashFrameInstance = SpringDSCrash.SDSCrashFrame(traceback)
    #app.SetTopWindow(SDSCrashFrameInstance)
    SDSCrashFrameInstance.MakeModal()
    SDSCrashFrameInstance.ShowModal()

class SpringDSSettingsFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: SpringDSSettingsFrame.__init__
        kwds["style"] = wx.CAPTION | wx.CLOSE_BOX | wx.SYSTEM_MENU | wx.SIMPLE_BORDER
        wx.Frame.__init__(self, *args, **kwds)
        self.SDSSBasePanel = wx.Panel(self, -1)
        self.SDSSHeaderImage = wx.StaticBitmap(self.SDSSBasePanel, -1, wx.Bitmap("SpringDSSettingsHeader.png", wx.BITMAP_TYPE_ANY))
        self.SDSSNotebook = wx.Notebook(self.SDSSBasePanel, -1, style=0)
        self.SDSSNetworkPane = wx.Panel(self.SDSSNotebook, -1)
        self.SDSSStaticIPLbl = wx.StaticText(self.SDSSNetworkPane, -1, "Static IP:")
        self.SDSSStaticIPTxtCtrl = wx.TextCtrl(self.SDSSNetworkPane, -1, SpringDSConfig.getCfgAbsStaticIP())
        self.SDSSStaticIPTeamNumCheckbox = wx.CheckBox(self.SDSSNetworkPane, -1, "Use FRC team number to determine static IP")
        self.SDSSubnetLbl = wx.StaticText(self.SDSSNetworkPane, -1, "Subnet:")
        self.SDSSubnetTxtCtrl = wx.TextCtrl(self.SDSSNetworkPane, -1, SpringDSConfig.getCfgSubnet())
        self.SDSSConnectionTypeLbl = wx.StaticText(self.SDSSNetworkPane, -1, "Connection Type:")
        self.SDSSConnectionTypeRadioBox = wx.RadioBox(self.SDSSNetworkPane, -1, "", choices=["LAN", "Wireless", "Custom NIC Selection..."], majorDimension=0, style=wx.RA_SPECIFY_ROWS)
        self.SDSSConnectionTypeRadioBox.Bind(wx.EVT_RADIOBOX, self.OnChangeConnectionType)
        
        self.SDSSNICSelectComboBox = wx.ComboBox(self.SDSSNetworkPane, -1, choices=["NIC #0"], style=wx.CB_DROPDOWN | wx.CB_DROPDOWN)
        self.SDSSNICSelectScanBtn = wx.Button(self.SDSSNetworkPane, -1, "Scan")
        self.SDSSFRCTeamNumLbl = wx.StaticText(self.SDSSNetworkPane, -1, "FRC Team Number:")
        self.SDSSFRCTeamNumTxtCtrl = wx.TextCtrl(self.SDSSNetworkPane, -1, SpringDSConfig.getCfgTeamID())
        self.SDSSPathsPane = wx.Panel(self.SDSSNotebook, -1)
        self.SDSSFRCDSPathLbl = wx.StaticText(self.SDSSPathsPane, -1, "FRC Driver Station Path:")
        
        #self.SDSSFRCDSPathTxtBox = wx.TextCtrl(self.SDSSPathsPane, -1, "")
        self.SDSSFRCDSPathTxtBox = filebrowse.FileBrowseButton(self.SDSSPathsPane, -1, labelText="", initialValue = SpringDSConfig.getCfgDriverStationPath())
        
        self.SDSSFRCDBPathLbl = wx.StaticText(self.SDSSPathsPane, -1, "FRC Dashboard Path:")
        
        #self.SDSSFRCDBPathTxtBox = wx.TextCtrl(self.SDSSPathsPane, -1, "")
        self.SDSSFRCDBPathTxtBox = filebrowse.FileBrowseButton(self.SDSSPathsPane, -1, labelText="", initialValue = SpringDSConfig.getCfgDashboardPath())
        
        self.SDSSAboutPane = wx.Panel(self.SDSSNotebook, -1)
        self.SDSSAboutVersionLbl = wx.StaticText(self.SDSSAboutPane, -1, "SpringDS v1.0b")
        self.SDSSDevelopedByLbl = wx.StaticText(self.SDSSAboutPane, -1, "Developed by:")
        self.SDSSDeveloperLbl = wx.StaticText(self.SDSSAboutPane, -1, "Albert Huang")
        self.SDSSCredit2Lbl = wx.StaticText(self.SDSSAboutPane, -1, "River Hill Robotics - The Incredible Hawk - Team #4067")
        self.SDSSAboutWebsiteLbl = wx.StaticText(self.SDSSAboutPane, -1, "Website:")
        #self.SDSSAboutURLLbl = wx.StaticText(self.SDSSAboutPane, -1, "URL")
        self.SDSSAboutURLLbl = hl.HyperLinkCtrl(self.SDSSAboutPane, wx.ID_ANY, "http://code.google.com/p/frcbot4067/", URL="http://code.google.com/p/frcbot4067/")
        
        self.SDSSOKBtn = wx.Button(self.SDSSBasePanel, wx.ID_OK, "")
        self.SDSSOKBtn.Bind(wx.EVT_BUTTON, self.OnOKButton)
        
        self.SDSSCancelBtn = wx.Button(self.SDSSBasePanel, wx.ID_CANCEL, "")
        self.SDSSCancelBtn.Bind(wx.EVT_BUTTON, self.OnCancelButton)
        
        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: SpringDSSettingsFrame.__set_properties
        self.SetTitle("SpringDS Settings")
        _icon = wx.EmptyIcon()
        _icon.CopyFromBitmap(wx.Bitmap("SpringDSSettingsIcon.ico", wx.BITMAP_TYPE_ANY))
        #self.SetIcon(_icon)
        self.SetIcon(wx.Icon("SpringDSSettingsIcon.ico", wx.BITMAP_TYPE_ICO, 16, 16))
        self.SDSSStaticIPLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.SDSSStaticIPTeamNumCheckbox.SetValue(SpringDSConfig.getCfgTeamIP() == "1")
        self.SDSSubnetLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.SDSSConnectionTypeLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        if (SpringDSConfig.getCfgNICType() == 'wireless'):
            self.SDSSConnectionTypeRadioBox.SetSelection(1)
            self.SDSSNICSelectComboBox.Enable(False)
            self.SDSSNICSelectScanBtn.Enable(False)
            self.SDSSNICSelectionIndex = 1
        elif (SpringDSConfig.getCfgNICType() == 'lan'):
            self.SDSSConnectionTypeRadioBox.SetSelection(0)
            self.SDSSNICSelectComboBox.Enable(False)
            self.SDSSNICSelectScanBtn.Enable(False)
            self.SDSSNICSelectionIndex = 0
        elif (SpringDSConfig.getCfgNICType() == 'nic'):
            #self.SDSSConnectionTypeRadioBox.SetSelection(2)
            #self.SDSSNICSelectComboBox.Enable(True)
            #self.SDSSNICSelectScanBtn.Enable(True)
            #self.SDSSNICSelectionIndex = 2
            self.SDSSConnectionTypeRadioBox.SetSelection(0)
            self.SDSSNICSelectComboBox.Enable(False)
            self.SDSSNICSelectScanBtn.Enable(False)
            self.SDSSNICSelectionIndex = 0
            MsgBox("The custom NIC selection feature of SpringDS is currently a work in progress. Please change the custom NIC option to another one.", "Error - SpringDS Settings", wx.ICON_WARNING, self)
        else:
            raise
        
        #self.SDSSConnectionTypeRadioBox.SetSelection(0)
        self.SDSSNICSelectComboBox.SetSelection(-1)
        self.SDSSFRCTeamNumLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.SDSSFRCDSPathLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.SDSSFRCDBPathLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.SDSSAboutVersionLbl.SetBackgroundColour(wx.Colour(0, 73, 130))
        self.SDSSAboutVersionLbl.SetForegroundColour(wx.Colour(255, 209, 41))
        self.SDSSAboutVersionLbl.SetFont(wx.Font(16, wx.MODERN, wx.NORMAL, wx.BOLD, 0, ""))
        self.SDSSDevelopedByLbl.SetBackgroundColour(wx.Colour(0, 73, 130))
        self.SDSSDevelopedByLbl.SetForegroundColour(wx.Colour(255, 209, 41))
        self.SDSSDevelopedByLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.SDSSDeveloperLbl.SetBackgroundColour(wx.Colour(0, 73, 130))
        self.SDSSDeveloperLbl.SetForegroundColour(wx.Colour(255, 209, 41))
        self.SDSSCredit2Lbl.SetBackgroundColour(wx.Colour(0, 73, 130))
        self.SDSSCredit2Lbl.SetForegroundColour(wx.Colour(255, 209, 41))
        self.SDSSAboutWebsiteLbl.SetBackgroundColour(wx.Colour(0, 73, 130))
        self.SDSSAboutWebsiteLbl.SetForegroundColour(wx.Colour(255, 209, 41))
        self.SDSSAboutWebsiteLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.SDSSAboutURLLbl.SetBackgroundColour(wx.Colour(0, 73, 130))
        self.SDSSAboutURLLbl.SetForegroundColour(wx.Colour(255, 209, 41))
        self.SDSSAboutPane.SetBackgroundColour(wx.Colour(0, 73, 130))
        self.SDSSOKBtn.SetDefault()
        self.SDSSBasePanel.SetBackgroundColour(wx.Colour(0, 52, 92))
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: SpringDSSettingsFrame.__do_layout
        SDSSBaseSizer = wx.BoxSizer(wx.VERTICAL)
        SDSSMainSizer = wx.FlexGridSizer(3, 1, 0, 0)
        SDSSButtonSizer = wx.FlexGridSizer(1, 2, 0, 0)
        SDSSAboutSizer = wx.FlexGridSizer(3, 1, 0, 0)
        SDSSAboutWebsiteSizer = wx.FlexGridSizer(1, 2, 0, 0)
        SDSSCreditSizer = wx.FlexGridSizer(2, 1, 0, 0)
        SDSSCreditDevSizer = wx.FlexGridSizer(1, 2, 0, 0)
        SDSSPathsSizer = wx.FlexGridSizer(2, 2, 0, 0)
        SDSSNetworkSizer = wx.FlexGridSizer(4, 2, 0, 0)
        SDSSConnectionTypeSizer = wx.FlexGridSizer(2, 1, 0, 0)
        SDSSNICSelectSizer = wx.FlexGridSizer(1, 2, 0, 0)
        SDSSStaticIPSizer = wx.FlexGridSizer(2, 1, 0, 0)
        SDSSMainSizer.Add(self.SDSSHeaderImage, 0, 0, 0)
        SDSSNetworkSizer.Add(self.SDSSStaticIPLbl, 0, wx.ALL, 4)
        SDSSStaticIPSizer.Add(self.SDSSStaticIPTxtCtrl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4)
        SDSSStaticIPSizer.Add(self.SDSSStaticIPTeamNumCheckbox, 0, wx.ALL | wx.EXPAND, 4)
        SDSSStaticIPSizer.AddGrowableRow(0)
        SDSSStaticIPSizer.AddGrowableRow(1)
        SDSSStaticIPSizer.AddGrowableCol(0)
        SDSSNetworkSizer.Add(SDSSStaticIPSizer, 1, wx.EXPAND, 0)
        SDSSNetworkSizer.Add(self.SDSSubnetLbl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4)
        SDSSNetworkSizer.Add(self.SDSSubnetTxtCtrl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4)
        SDSSNetworkSizer.Add(self.SDSSConnectionTypeLbl, 0, wx.ALL, 4)
        SDSSConnectionTypeSizer.Add(self.SDSSConnectionTypeRadioBox, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 4)
        SDSSNICSelectSizer.Add(self.SDSSNICSelectComboBox, 0, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 4)
        SDSSNICSelectSizer.Add(self.SDSSNICSelectScanBtn, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 4)
        SDSSNICSelectSizer.AddGrowableRow(0)
        SDSSNICSelectSizer.AddGrowableCol(0)
        SDSSConnectionTypeSizer.Add(SDSSNICSelectSizer, 1, wx.EXPAND, 0)
        SDSSNetworkSizer.Add(SDSSConnectionTypeSizer, 1, wx.EXPAND, 0)
        SDSSNetworkSizer.Add(self.SDSSFRCTeamNumLbl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4)
        SDSSNetworkSizer.Add(self.SDSSFRCTeamNumTxtCtrl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4)
        self.SDSSNetworkPane.SetSizer(SDSSNetworkSizer)
        SDSSNetworkSizer.AddGrowableRow(0)
        SDSSNetworkSizer.AddGrowableCol(1)
        SDSSPathsSizer.Add(self.SDSSFRCDSPathLbl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4)
        SDSSPathsSizer.Add(self.SDSSFRCDSPathTxtBox, 0, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_VERTICAL, 4)
        SDSSPathsSizer.Add(self.SDSSFRCDBPathLbl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4)
        SDSSPathsSizer.Add(self.SDSSFRCDBPathTxtBox, 0, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_VERTICAL, 4)
        self.SDSSPathsPane.SetSizer(SDSSPathsSizer)
        SDSSAboutSizer.Add(self.SDSSAboutVersionLbl, 0, wx.ALL, 4)
        SDSSCreditDevSizer.Add(self.SDSSDevelopedByLbl, 0, wx.ALL, 4)
        SDSSCreditDevSizer.Add(self.SDSSDeveloperLbl, 0, wx.ALL, 4)
        SDSSCreditDevSizer.AddGrowableRow(0)
        SDSSCreditSizer.Add(SDSSCreditDevSizer, 1, wx.EXPAND, 0)
        SDSSCreditSizer.Add(self.SDSSCredit2Lbl, 0, wx.ALL, 4)
        SDSSCreditSizer.AddGrowableCol(0)
        SDSSAboutSizer.Add(SDSSCreditSizer, 1, wx.EXPAND, 0)
        SDSSAboutWebsiteSizer.Add(self.SDSSAboutWebsiteLbl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4)
        SDSSAboutWebsiteSizer.Add(self.SDSSAboutURLLbl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4)
        SDSSAboutWebsiteSizer.AddGrowableCol(1)
        SDSSAboutSizer.Add(SDSSAboutWebsiteSizer, 1, wx.EXPAND, 0)
        self.SDSSAboutPane.SetSizer(SDSSAboutSizer)
        SDSSAboutSizer.AddGrowableRow(1)
        SDSSAboutSizer.AddGrowableCol(0)
        self.SDSSNotebook.AddPage(self.SDSSNetworkPane, "Network")
        self.SDSSNotebook.AddPage(self.SDSSPathsPane, "Paths")
        self.SDSSNotebook.AddPage(self.SDSSAboutPane, "About...")
        SDSSMainSizer.Add(self.SDSSNotebook, 1, wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND, 4)
        SDSSButtonSizer.Add(self.SDSSOKBtn, 0, wx.ALL, 4)
        SDSSButtonSizer.Add(self.SDSSCancelBtn, 0, wx.ALL, 4)
        SDSSMainSizer.Add(SDSSButtonSizer, 1, wx.ALL | wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 4)
        self.SDSSBasePanel.SetSizer(SDSSMainSizer)
        SDSSMainSizer.AddGrowableRow(1)
        SDSSMainSizer.AddGrowableCol(0)
        SDSSBaseSizer.Add(self.SDSSBasePanel, 1, wx.EXPAND, 0)
        self.SetSizer(SDSSBaseSizer)
        SDSSBaseSizer.Fit(self)
        self.Layout()
        # end wxGlade
    def OnCancelButton(self, event):
        # Just exit!
        self.Destroy()
    def OnOKButton(self, event):
        # Save the settings!
        try:
            print "[SpringDSSettings] Saving static IP..."
            SpringDSConfig.setCfgAbsStaticIP(self.SDSSStaticIPTxtCtrl.GetValue())
            print "[SpringDSSettings] Saving team number to IP option..."
            SpringDSConfig.setCfgTeamIP((self.SDSSStaticIPTeamNumCheckbox.GetValue() and "1") or "0")
            print "[SpringDSSettings] Saving subnet..."
            SpringDSConfig.setCfgSubnet(self.SDSSubnetTxtCtrl.GetValue())
            print "[SpringDSSettings] Saving FRC team number..."
            SpringDSConfig.setCfgTeamID(self.SDSSFRCTeamNumTxtCtrl.GetValue())
            print "[SpringDSSettings] Saving NIC type..."
            if (self.SDSSConnectionTypeRadioBox.GetSelection() == 1):
                print "[SpringDSSettings]   Wireless"
                SpringDSConfig.setCfgNICType("wireless")
            elif (self.SDSSConnectionTypeRadioBox.GetSelection() == 0):
                print "[SpringDSSettings]   LAN"
                SpringDSConfig.setCfgNICType("lan")
            elif (self.SDSSConnectionTypeRadioBox.GetSelection() == 2):
                #self.SDSSNICSelectComboBox.Enable(True)
                #self.SDSSNICSelectScanBtn.Enable(True)
                # Disabled for now.
                MsgBox("You're sneaky! (You should've been stopped before from selecting custom NICs.)\nThis feature of SpringDS is currently a work in progress. This option can not be selected at this time.", "Error - SpringDS Settings", wx.ICON_ERROR, self)
                # ...and don't save anything.
            else:
                raise
            print "[SpringDSSettings] Saving driver station path..."
            SpringDSConfig.setCfgDriverStationPath(self.SDSSFRCDSPathTxtBox.GetValue())
            print "[SpringDSSettings] Saving dashboard path..."
            SpringDSConfig.setCfgDashboardPath(self.SDSSFRCDBPathTxtBox.GetValue())
            print "[SpringDSSettings] ** Saving config file... **"
            SpringDSConfig.writeConfig()
            print "[SpringDSSettings] All done! Exiting."
            self.Destroy()
        except:
            import traceback
            ErrorBox("An error occurred while saving the SpringDS configuration. \n"+"".join(traceback.format_exc()))
        
    def OnChangeConnectionType(self, event):
        if (self.SDSSConnectionTypeRadioBox.GetSelection() == 1) or (self.SDSSConnectionTypeRadioBox.GetSelection() == 0):
            self.SDSSNICSelectComboBox.Enable(False)
            self.SDSSNICSelectScanBtn.Enable(False)
            self.SDSSNICSelectionIndex = self.SDSSConnectionTypeRadioBox.GetSelection()
        elif (self.SDSSConnectionTypeRadioBox.GetSelection() == 2):
            #self.SDSSNICSelectComboBox.Enable(True)
            #self.SDSSNICSelectScanBtn.Enable(True)
            # Disabled for now.
            MsgBox("This feature of SpringDS is currently a work in progress. This option can not be selected at this time.", "Error - SpringDS Settings", wx.ICON_ERROR, self)
            self.SDSSConnectionTypeRadioBox.SetSelection(self.SDSSNICSelectionIndex)
        else:
            raise

# end of class SpringDSSettingsFrame
if __name__ == "__main__":
    try:
        SpringDSConfig.initConfig()
    except:
        MsgBox("Couldn't load SpringDS configuration!", "Error - SpringDS", wx.ICON_ERROR)
        import traceback
        ErrorBox("".join(traceback.format_exc()))
        exit()
    try:
        app = wx.PySimpleApp(0)
        wx.InitAllImageHandlers()
        SpringDSSettingsFrameInstance = SpringDSSettingsFrame(None, -1, "")
        app.SetTopWindow(SpringDSSettingsFrameInstance)
        SpringDSSettingsFrameInstance.Show()
        app.MainLoop()
    except:
        import traceback
        ErrorBox("".join(traceback.format_exc()))
        exit()